window.umSdk = {
  status: 'ready',
  user: {},
  config: function (params) {},
  setCanInterceptBackKey: function (callback) {
    if (callback && callback.success) {
      callback.success();
    }
  },
  ready: function (callback) {
    this.initToken();
    if (window.plus) {
      callback();
    } else {
      document.addEventListener('plusready', function () {
        callback();
      });
    }
  },
  initToken: function () {
    const xhr = new XMLHttpRequest();
    const url = 'http://m.championsoft.net:60000/mobileApi/umsdk/getToken';
    xhr.open('post', url, false);
    xhr.send();
    window.umSdk.user = JSON.parse(xhr.responseText);

    localStorage.setItem("gzlp_refresh_token", window.umSdk.user.refresh_token);
    localStorage.setItem("gzlp_access_token", window.umSdk.user.access_token);
    localStorage.setItem("projectNavParams", window.umSdk.user.projectNavParams);
    localStorage.setItem(
      "userInfo",
      JSON.stringify({
        "access_token": window.umSdk.user.access_token,
        "token_type": "bearer",
        "expires_in": 21599,
        "refresh_token": window.umSdk.user.refresh_token,
        "as:client_id": "",
        "userName": window.umSdk.user.userName,
        "loginName": window.umSdk.user.loginName,
        "shortname": window.umSdk.user.shortname,
        "deptcode": window.umSdk.user.deptcode,
        "deptname": window.umSdk.user.deptname,
        ".issued": new Date(),
        ".expires": new Date(new Date().getTime() + 1000000000)
      })
    );
  },
  getToken: function (callback) {
    if (callback && callback.success) {
      callback.success({
        "token": window.umSdk.user.token
      });
    }
  },
  getH5Data: function (callback) {
    callback.success(localStorage.getItem(callback.key));
  },
  saveH5Data: function (callback) {
    callback.success(localStorage.setItem(callback.key, callback.value));
  },
  getSessionStorage: function (callback) {
    if (callback.key == "lcm.userinfo") {
      callback.callback({
        "responseData": "{\"data\":{\"eid\":\"526932120254025728\",\"mobile\":\"" + window.umSdk.user.loginName + "\",\"tokenId\":\"" + window.umSdk.user.token + "\",\"userId\":\"" + window.umSdk.user.userId + "\",\"userName\":\"" + window.umSdk.user.userName + "\"},\"msg\":\"成功\",\"status\":\"success\"}",
        "responseId": "cb_7_1659414788204"
      });
    } else {
      callback.success ? callback.success({
        tokenId: window.umSdk.user.token,
        phone: window.umSdk.user.loginName,
        userName: window.umSdk.user.userName,
        mobile: window.umSdk.user.loginName
      }) : null;
    }
  },
  on: function () {

  },
  off: function () {

  },
  preRefresh: function () {
    let wv = window.plus.webview.getDisplayWebview()[0];
    if (wv.preloading) {
      wv.hide("slide-out-bottom");
    } else {
      wv.close("slide-out-bottom");
    }
  },
  setNavigation: function (params) {
    window.umSdk.ready(function () {
      let wv = window.plus.webview.currentWebview();
      let tn = wv.getTitleNView();
      if (params.hidden != 1) {
        let style = {};
        if (params.backgroundImage && params.backgroundImage.startsWith("http")) {
          var dtask = plus.downloader.createDownload(params.backgroundImage, {}, function (d, status) {
            // 下载完成
            style = {
              titleNView: {
                titleText: params.title,
                titleColor: params.titleColor,
                titleSize: params.fontSize,
                backgroundColor: params.backgroundColor,
                backgroundImage: params.backgroundImage || "",
              }
            };
            if (status == 200) {
              style.titleNView.backgroundImage = d.filename;
            }
            //}
            wv.setStyle(style);
            if (tn && !tn.isVisible()) {
              tn.show();
            }
          });
          dtask.start();
        } else {
          // if (params.type == 2) {
          //   style = {
          //     titleNView: {
          //       subtitleText: params.title,
          //       subtitleColor: params.titleColor,
          //       subtitleSize: params.fontSize,
          //       backgroundColor: params.backgroundColor,
          //       backgroundImage: params.backgroundImage,
          //     }
          //   };
          // } else {
          style = {
            titleNView: {
              titleText: params.title,
              titleColor: params.titleColor,
              titleSize: params.fontSize,
              backgroundColor: params.backgroundColor,
              backgroundImage: params.backgroundImage || "",
            }
          };
          //}
          wv.setStyle(style);
          if (tn && !tn.isVisible()) {
            tn.show();
          }
        }
      } else if (tn) {
        tn.close();
      }
      params.success ? params.success() : null;
    });
  },
  openLink: function (params) {
    // let p = {
    // 	isHome: false, // 当前页面是否为首页（首页不可返回)，默认值：false
    // 	success: function() {},
    // 	fail: function(err) {}
    // }
    let mapp = {
      appCode: params.title || Math.random(),
      appName: params.title || "",
      appLink: params.url,
      preloading: 0,
      isLogin: 1,
      cssText: "",
      listenResourceJs: "",
      backJS: "",
      isTitleBar: params.hidden == "0",
      publicKey: "",
      privateKey: "",
    };
    plus.webview.getLaunchWebview().evalJS('vue.$framework.miniApp.open(' + JSON.stringify(mapp) + ',null,"white");');
    params.success();
  },
  scanFile: function (params) {
    // downloadurl: "", // 文件预览网络地址
    // filename: "", // 文件名（需要携带文件后缀）
    // success: function () {},
    // fail: function (err) {}
    try {
      var fileType = params.filename.substring(params.filename.lastIndexOf(".") + 1);
      if (["png", "jpg"].includes(fileType)) {
        params.imgs = [params.downloadurl];
        window.umSdk.showPhotos(params);
      } else {
        var view = plus.webview.create('_www/static/onlyoffice/viewer.html', "文档预览", {
          popGesture: 'none',
          scrollIndicator: 'none',
          scalable: false,
          backButtonAutoControl: 'close',
        }, {
          option: {
            title: params.filename,
            fileType: fileType,
            url: params.downloadurl
          },
          user: plus.webview.currentWebview().user
        });
        view.show("slide-in-bottom");
      }
    } catch (error) {
      params.fail ? params.fail(error) : null;
    }
  },
  // 预览图片
  showPhotos: function (params) {
    try {
      if (window.plus) {
        plus.nativeUI.previewImage(params.imgs, {
          current: params.index || 0,
          loop: params.loop,
          onLongPress: params.onLongPress || null,
        });
        params.success ? params.success() : null;
      }
    } catch (error) {
      params.fail ? params.fail(error) : null;
    }
  },
  getLocation: function (params) {
    if (window.plus) {
      plus.geolocation.getCurrentPosition(success => {
        params.success ? params.success(success) : null;
        console.log(JSON.stringify(success));
      }, error => {
        params.fail ? params.fail(error) : null;
        console.log(JSON.stringify(error));
      }, {
        coordsType: "bd09ll",
        enableHighAccuracy: true,
        timeout: 2000,
      });
    }
  },
  // 保存图片
  savePhotoToAlbum: function (params) {
    try {
      if (window.plus) {
        plus.gallery.save(params.downloadurl, params.success, params.fail)
      }
    } catch (e) {
      //TODO handle the exception
      params.fail(e);
    }
  },

  // 拨打电话
  call: function (params) {
    if (window.plus) {
      plus.device.dial(params.phone);
      params.success ? params.success() : null;
    }
    params.fail ? params.fail() : null;
  },
  fileUpload: function (params) {
    plus.nativeUI.alert("适配层尚未适配上传方法，请等待适配...");
  },
  callHandler: function (key, params) {
    window.umSdk.ready(function () {
      if (window.umSdk[key]) {
        window.umSdk[key](params);
      } else {
        console.error(key, params);
      }
    });
  }
};
